package com.tc.dispatch.web.schedule.order;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import com.tc.dispatch.gsalgorithm.spec.spec;
import com.tc.dispatch.gsalgorithm.spec.specConst;
import com.tc.dispatch.gsservice.basic.common.tcdate;
import com.tc.dispatch.gsservice.ejb.GSServiceLocal;
import com.tc.dispatch.gsservice.exception.GSException;
import com.tc.dispatch.gsservice.model.GSConstants;
import com.tc.dispatch.gsservice.model.OrderSumSub;
import com.tc.dispatch.gsservice.model.OtherConstants;
import com.tc.dispatch.web.gsservice.gsHelper;
import com.tc.dispatch.web.util.DateJsonValueProcessor;
import com.tc.dispatch.web.util.tools;
import com.tc.dispatch.gsalgorithm.spec.specConst;

public class orderInfo extends HttpServlet {
	int i=0;
	/**
	 * Constructor of the object.
	 */
	public orderInfo() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
		i--;
		System.out.println("destroy:"+i);
	}

	/**
	 * The doGet method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html; charset=utf-8");
		// response.setCharacterEncoding("utf-8");
		PrintWriter out = response.getWriter();
		
		out.flush();

		out.close();
	}

	/**
	 * The doPost method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to
	 * post.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html; charset=utf-8");
		// response.setCharacterEncoding("utf-8");
		PrintWriter out = response.getWriter();
		String action = request.getParameter("action");
		GSServiceLocal gss = gsHelper.getGSServiceLocal();
		HttpSession sess = request.getSession();
		i++;
		System.out.println("doPost:"+i);
		if (action.equals("list")) {
			

			String dateFrom = request.getParameter("dateFrom");
			String dateTo = request.getParameter("dateTo");
			
			
			Date dateF;
			Date dateT;
			String sortType = request.getParameter("sortType");
			if (sortType == null||sortType.equals(""))
				{
					Object obj=sess.getAttribute("sortType");
					if(obj!=null)
						sortType = (String)obj;
					else
						sortType="";
				}
			if (dateFrom == null || dateFrom.equals(""))
				{
					//dateF = Calendar.getInstance().getTime();
					Object obj=sess.getAttribute("dateFrom");
					if(obj!=null)
						dateF=tools.stringToDate((String)obj);
					else
						dateF = Calendar.getInstance().getTime();
					dateFrom=tools.dateToString(dateF);
				}
			else
				dateF = tools.stringToDate(dateFrom);
			if (dateTo == null || dateTo.equals(""))
				{
				Object obj=sess.getAttribute("dateTo");
				if(obj!=null)
					dateT=tools.stringToDate((String)obj);
				else
					dateT = Calendar.getInstance().getTime();
				dateTo=tools.dateToString(dateT);
				
				}
			else
				dateT = tools.stringToDate(dateTo);
			if(sortType.equals("dakong"))
				sortType="taokong";
			System.out.println("sortType is:" + sortType);
			
			dateF = tcdate.getStartFromDate(dateF);
			dateT = tcdate.getEndFromDate(dateT);

			String start = request.getParameter("start");
			String limit = request.getParameter("limit");
			String newList = request.getParameter("isNew");

			List ret = new ArrayList();
			if (newList != null) {
				try {
					ret = gss.getFinishedPro(dateF, dateT, sortType);
					sess.removeAttribute("finishedList");
					sess.setAttribute("finishedList", ret);

				} catch (GSException e) {
					System.out.println("GSException:" + e.getMessage());
					// response.sendRedirect("orderError.jsp?error="+e.getErrorCode());
					out.print("{success:false, data:'false'}");
				}
			} else {
				ret = (List) sess.getAttribute("finishedList");
			}
			
			sess.setAttribute("dateFrom", dateFrom);
			sess.setAttribute("dateTo", dateTo);
			sess.setAttribute("sortType", sortType);

			int startIndex = Integer.parseInt(start);
			int endIndex = (Integer.parseInt(start) + Integer.parseInt(limit));

			if (endIndex > ret.size())
				endIndex = ret.size();
			JSONObject json = new JSONObject();
			JsonConfig cfg = new JsonConfig();
			cfg.registerJsonValueProcessor(java.util.Date.class,
					new DateJsonValueProcessor());
			cfg.registerJsonValueProcessor(java.sql.Date.class,
					new DateJsonValueProcessor());

			// BeanUtils.copyProperties();
			json.put("totalProperty", new Integer(ret.size()));
			ret = ret.subList(startIndex, endIndex);
			JSONArray arr = JSONArray.fromObject(ret.toArray(), cfg);
			json.put("root", arr);
			response.getWriter().print(json);
		} else if (action.equals("update")) {
			String amount = request.getParameter("amount");
			String dateFrom = request.getParameter("dateFrom");
			String dateTo = request.getParameter("dateTo");
			String sortType = request.getParameter("sortType");

			/*
			 * if(sortType.equals("圆柱")) sortType=specConst.YuanZhu; else
			 * if(sortType.equals("方块")) sortType=specConst.Fangkuai; else
			 * sortType=specConst.UnparseSpec;
			 */
				
			try {
				OtherConstants oc=(OtherConstants)gss.findOtherConstants(" where name='"+GSConstants.AMOUNT+"'").get(0);
				oc.setConstant(Float.valueOf(amount));
				gss.updateOtherConstants(oc);
				//gss.setAmount(Integer.parseInt(amount));
			} catch (NumberFormatException nfe) {
				System.out.println("NumberFormatException:" + nfe.getMessage());
			} catch (GSException e) {
				System.out.println("GSException:" + e.getMessage());
				// response.sendRedirect("orderError.jsp?error="+e.getErrorCode());
				out.print("{success:false, data:'false'}");
			}
			Date dateF;
			Date dateT;
			if (sortType == null)
				sortType = "";
			if (dateFrom == null || dateFrom.equals(""))
				dateF = Calendar.getInstance().getTime();
			else
				dateF = tools.stringToDate(dateFrom);
			if (dateTo == null || dateTo.equals(""))
				dateT = Calendar.getInstance().getTime();
			else
				dateT = tools.stringToDate(dateTo);
			dateF = tcdate.getStartFromDate(dateF);
			dateT = tcdate.getEndFromDate(dateT);

			try {
				List ret = gss.getFinishedPro(dateF, dateT, sortType);
				sess.removeAttribute("finishedList");
				sess.setAttribute("finishedList", ret);

			} catch (GSException e) {
				System.out.println("GSException:"+e.getMessage());
				out.print("{success:false, data:'false'}");
			}

		}
		out.flush();
		out.close();

	}

	/**
	 * Initialization of the servlet. <br>
	 * 
	 * @throws ServletException
	 *             if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
		i++;
		System.out.println("init:"+i);
	}

	public int getAmount() {
		int ret = 0;
		GSServiceLocal gss = gsHelper.getGSServiceLocal();
		try {
			OtherConstants oc=(OtherConstants)gss.findOtherConstants(" where name='"+GSConstants.AMOUNT+"'").get(0);
			ret=oc.getConstant().intValue();
		} catch (GSException gse) {
			return 0;
		}
		return ret;

	}

}
